package com.itheima.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.base.Area;
import com.itheima.bos.domain.base.FixedArea;
import com.itheima.bos.domain.base.SubArea;
import com.itheima.bos.service.SubAreaService;
import com.itheima.bos.web.action.common.BaseAction;

@ParentPackage(value="json-default")
@Namespace("/subArea")
@Controller
@Scope("prototype")
public class SubAreaAction extends BaseAction<SubArea> {

	@Autowired
	private SubAreaService subAreaService;
	
	private File file;
	
	public void setFile(File file) {
		this.file = file;
	}

	@Action(value="subArea_importData",results={@Result(name="success",type="redirect",location="../pages/base/sub_area.html")})
	public String subArea_importData(){
		List<SubArea> list = new ArrayList<SubArea>();
		try {
			HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
			HSSFSheet sheetAt = wb.getSheetAt(0);
			for (Row row : sheetAt) {
				if(row.getRowNum() == 0){
					continue;
				}
				SubArea subArea = new SubArea();
				subArea.setId(row.getCell(0).getStringCellValue());//id
				FixedArea fixedArea = new FixedArea();
				fixedArea.setId(row.getCell(1).getStringCellValue());
				subArea.setFixedArea(fixedArea);//定区
				Area area = new Area();
				area.setId(row.getCell(2).getStringCellValue());
				subArea.setArea(area);//区域
				subArea.setKeyWords(row.getCell(3).getStringCellValue());//关键字
				subArea.setStartNum(row.getCell(4).getStringCellValue());//起始号
				subArea.setEndNum(row.getCell(5).getStringCellValue());//结束号
				subArea.setSingle(row.getCell(6).getStringCellValue().toCharArray()[0]);//单双号
				subArea.setAssistKeyWords(row.getCell(7).getStringCellValue());// 辅助关键字（位置信息）
				list.add(subArea);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		subAreaService.importData(list);
		return SUCCESS;
	}
	
	@Action(value="subArea_pageQuery",results={@Result(name="success",type="json")})
	public String subArea_pageQuery(){
		Pageable pageable = new PageRequest(page - 1, rows);
		Page page = subAreaService.pageQuery(pageable);
		pushPageDateToValueStack(page);
		return SUCCESS;
	}
}
